package com.imooc.concurrency.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

@Slf4j
public class SemaphoreTest3 {

    static int threadCount = 20;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();

        Semaphore semaphore = new Semaphore(3);

        for(int i = 0;i < threadCount;i ++) {
            final int num = i;
            executorService.execute(() -> {
                try {
                    if(semaphore.tryAcquire(5, TimeUnit.SECONDS)) { // 在指定时间内尝试获取许可
                        test(num);
                        semaphore.release(1); // 释放一个许可
                    }
                } catch (InterruptedException e) {
                    log.info("exception {}", e);
                }
            });
        }
        executorService.shutdown();
    }

    public static void test(int num) throws InterruptedException {
        log.info("num: {}", num);
        Thread.sleep(1000);
    }

}
